﻿using Microsoft.Win32;
using Newtonsoft.Json;
using Nex_CSharp_Demo.utils;
using Nex_CSharp_Demo.ViewModel;
using NexC_Sharp.Services;
using RobotPerCeption.Entity;
using RobotPerCeption.utils;
using RobotPerCeption.ViewModel;
using System.IO;
using System.Text;
using System.Windows;
using System.Windows.Controls;

namespace RobotPerCeption
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {


        public static double[] position = { 0 };

        public Dictionary<int, Grid> gridsToggle = new Dictionary<int, Grid>();

        List<DataFileViewModel> fileLists = null;

        Window mainWindow = null;
        public static string roboteName = "HJ001";

        public static bool connect_tag = false;
        public SiFuStatusCtr sifuCtr = null;
        public Student stu;

        public RoboteConnect connect;


        public DataFileViewModel operations = new DataFileViewModel();


        public MainWindow()
        {
            InitializeComponent();
            this.ipt_ip_address.Text = "192.168.1.13";
            this.ipt_ports.Text = "6001";

            mainWindow = Application.Current.MainWindow;


            fileLists = new List<DataFileViewModel>();

            this.fileList.Items.Clear();
            this.fileList.ItemsSource = fileLists;





        }





        protected override void OnContentRendered(EventArgs e)
        {
            Console.WriteLine("the resource has  finish");
            connect = new RoboteConnect(this.ipt_ip_address.Text, this.ipt_ip_address.Text);
            this.radio_status_stop.Checked += sifuRadioBtnCheck;
            this.radio_status_standby.Checked += sifuRadioBtnCheck;
            this.radio_status_runing.Checked += sifuRadioBtnCheck;
            this.robote_sijiao.Checked += robote_model_change;
            this.robote_runing.Checked += robote_model_change;
            this.robote_telnet.Checked += robote_model_change;


            initListen();
        }
        public void initListen()
        {


            RadioButton sijiao = this.robote_sijiao;
            RadioButton runing = this.robote_runing;
            RadioButton telnet = this.robote_telnet;

            Label modelLab = this.lab_robot_model_status;
            RoboteModelStatusLinsten linsten = new RoboteModelStatusLinsten(modelLab, runing, sijiao, telnet);
            ComboBox combo = (ComboBox)this.cbx_select;
            //自动开启侦听
            combo.SelectedIndex = 1;
            //机器人模式侦听
            linsten.linstenRun();





        }


        private void btn_to_connect_Click(object sender, RoutedEventArgs e)
        {
            Button btn_connect = this.btn_to_connect;
            string ipaddress = this.ipt_ip_address.Text;

            string port = this.ipt_ports.Text;
            if (string.IsNullOrEmpty(ipaddress.Trim()) || string.IsNullOrEmpty(port.Trim()))
            {
                MessageBox.Show("请输入正确的IP地址或端口号");
            }

            // 0 - 成功，-1 - 失败，-3 - 参数错误，-4 - 存在相同的机器人key
            int result =
                Nex.connect_robot(ipaddress, port, roboteName);
            // 0;
            switch (result)
            {
                case 1:
                    {
                        connect.hasConnect(btn_connect, connect_tag = false, this.lab_robot_ac_connect, roboteName);
                        break;
                    }
                case 0:
                    {
                        connect.hasConnect(btn_connect, connect_tag = true, this.lab_robot_ac_connect, roboteName);
                        //连接成功  初始化伺服状态
                        sifuCtr = new SiFuStatusCtr();
                        sifuCtr.tcpAfterInitSifu(roboteName, this.lab_sifu_cur_status, this.radio_status_stop, this.radio_status_standby, this.radio_status_runing);
                        break;
                    }
                case -3:
                    {
                        connect.hasConnect(btn_connect, connect_tag = false, this.lab_robot_ac_connect, roboteName);
                        break;
                    }
                case -4:
                    {
                        connect.hasConnect(btn_connect, connect_tag = false, this.lab_robot_ac_connect, roboteName);
                        break;
                    }


            }
        }




        private void btn_clear_err_Click(object sender, RoutedEventArgs e)
        {
            int result = Nex.clear_error(roboteName);
            /*Color color = new Color();

            Brush brush = new SolidColorBrush(Color.FromRgb(32, 218, 16));
            this.lab_note_clear.Foreground = brush;*/


            if (result != -2)
            {
                MessageBox.Show("清除成功" + "");
            }
            else
            {
                MessageBox.Show("清除失败" + "");
            }

        }

        private void ListBoxItem_Selected(object sender, RoutedEventArgs e)
        {
            Console.Write("selected");


        }
        private void cbx_select_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            RobotePosistionRanderZJ render = null;
            bool lab_tag = false;
            bool ipt_tag = false;
            ComboBox box = (ComboBox)sender;
            int index = box.SelectedIndex; //选择的下标
            //机器人坐标系 lab
            Label? lab_a = null;
            Label? lab_b = null;
            Label? lab_c = null;
            Label? lab_x = null;
            Label? lab_y = null;
            Label? lab_z = null;
            object elementx = LogicalTreeHelper.FindLogicalNode(this, "lab_zj_zb_x");
            object elementy = LogicalTreeHelper.FindLogicalNode(this, "lab_zj_zb_y");
            object elementz = LogicalTreeHelper.FindLogicalNode(this, "lab_zj_zb_z");
            object elementa = LogicalTreeHelper.FindLogicalNode(this, "lab_zj_zb_a");
            object elementb = LogicalTreeHelper.FindLogicalNode(this, "lab_zj_zb_b");
            object elementc = LogicalTreeHelper.FindLogicalNode(this, "lab_zj_zb_c");

            //机器人关节坐标值
            TextBox? ipt_a = null;
            TextBox? ipt_b = null;
            TextBox? ipt_c = null;
            TextBox? ipt_x = null;
            TextBox? ipt_y = null;
            TextBox? ipt_z = null;

            object ipt_elementx = LogicalTreeHelper.FindLogicalNode(this, "ipt_zb_x");
            object ipt_elementy = LogicalTreeHelper.FindLogicalNode(this, "ipt_zb_y");
            object ipt_elementz = LogicalTreeHelper.FindLogicalNode(this, "ipt_zb_z");
            object ipt_elementa = LogicalTreeHelper.FindLogicalNode(this, "ipt_zb_a");
            object ipt_elementb = LogicalTreeHelper.FindLogicalNode(this, "ipt_zb_b");
            object ipt_elementc = LogicalTreeHelper.FindLogicalNode(this, "ipt_zb_c");

            //lab元素强制转换
            if (elementx != null && elementx is Label &&
                elementy != null && elementy is Label &&
                elementz != null && elementz is Label &&
                elementa != null && elementa is Label &&
                elementb != null && elementb is Label &&
                elementc != null && elementc is Label)
            {

                lab_a = (Label)elementa;
                lab_b = (Label)elementb;
                lab_c = (Label)elementc;
                lab_x = (Label)elementx;
                lab_y = (Label)elementy;
                lab_z = (Label)elementz;
                render = new RobotePosistionRanderZJ();
                render.loadElementZJ(index, lab_x, lab_y, lab_z, lab_a, lab_b, lab_c);
                lab_tag = true;
            }




            //textBox元素强制转换

            if (ipt_elementx != null && ipt_elementx is TextBox &&
                 ipt_elementy != null && ipt_elementy is TextBox &&
                 ipt_elementz != null && ipt_elementz is TextBox &&
                 ipt_elementa != null && ipt_elementa is TextBox &&
                 ipt_elementb != null && ipt_elementb is TextBox &&
                 ipt_elementc != null && ipt_elementc is TextBox)
            {

                ipt_a = (TextBox)ipt_elementa;
                ipt_b = (TextBox)ipt_elementb;
                ipt_c = (TextBox)ipt_elementc;
                ipt_x = (TextBox)ipt_elementx;
                ipt_y = (TextBox)ipt_elementy;
                ipt_z = (TextBox)ipt_elementz;

                ipt_tag = true;

            }

            if (ipt_tag && lab_tag)
            {
                Dictionary<int, PositionThreadInfo> info = ThreadUtils.positonThread;
                //互斥操作 停止所有线程
                int removeCount = ThreadUtils.keyItratorRemove();
                //设置机器人坐标系
                int result = Nex.set_current_coord(index, roboteName);
                /* if (result != 0)
                 {
                     MessageBox.Show("切换坐标系失败");
                 }*/

                //开起对应坐标系线程
                ThreadData data = new ThreadData(200, index
                    , ipt_x, ipt_y, ipt_z, ipt_a, ipt_b, ipt_c,
                    index);
                data.Run(index);
            }
            else
            {

                Console.WriteLine("waiting..........");
            }

        }

        private void btn_power_up_Click(object sender, RoutedEventArgs e)
        {
            //伺服上电
            Nex.set_servo_poweron(MainWindow.roboteName);
            //上电以后为运行态
            int result_runing = Nex.set_servo_state(1, MainWindow.roboteName);
            if (result_runing != 1)
            {
                MessageBox.Show("请将伺服切换为就绪状态");
            }
        }
        /// <summary>
        ///      机器人下电成功后调用 get_servo_state()为1伺服就绪状态
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_power_down_Click(object sender, RoutedEventArgs e)
        {
            //伺服下电
            Nex.set_servo_poweroff(MainWindow.roboteName);
            //
            this.lab_sifu_cur_status.Content = "就绪状态";

            this.radio_status_standby.IsChecked = true;
        }


        public void sifuRadioBtnCheck(object sender, RoutedEventArgs e)
        {

            RadioButton radioButton = sender as RadioButton;
            // 0 停止 1 就绪
            if (radioButton.Content.Equals("停止状态"))
            {
                Nex.set_servo_state(0, roboteName);
            }
            if (radioButton.Content.Equals("就绪状态"))
            {
                Nex.set_servo_state(1, roboteName);

            }
        }

        public void sifuRadioBtnUnCheck(object sender, RoutedEventArgs e)
        {
            /* RadioButton radioButton = sender as RadioButton;
            *//* Console.WriteLine(radioButton.Content);*/


        }

        private void Slider_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
        {

            int curValue = Convert.ToInt32(e.NewValue);
            int respone = Nex.set_speed(curValue, roboteName);
            if (this.slider_value != null)
            {
                this.slider_value.Content = curValue + "/Speed";
            }
            if (respone == -2)
            {

                //MessageBox.Show("机器人已断开连接");
            }




        }

        private void robote_model_change(object sender, RoutedEventArgs e)
        {
            RadioButton btn = sender as RadioButton;
            int response = 0;
            if (btn != null)
            {
                string status = null;
                //模式 0：示教 1：远程 2：运行

                if (btn.Content.Equals("示教"))
                {
                    response = Nex.set_current_mode(0, roboteName);
                }
                else if (btn.Content.Equals("远程"))
                {
                    response = Nex.set_current_mode(1, roboteName);
                }
                else if (btn.Content.Equals("运行"))
                {
                    response = Nex.set_current_mode(2, roboteName);
                }


                /* btn.IsChecked = true;
                 this.lab_robot_model_status.Content = btn.Content + "模式";*/


                if (response != -2)
                {
                    btn.IsChecked = true;
                    this.lab_robot_model_status.Content = btn.Content + "模式";
                }
            }
        }

        /// <summary>
        ///获取当前行 文件名称
        //根据文件名称 加载文件内容 
        //文件内容包含 文件名称  格式  上传日期  机器人指令内容
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        //ListItem选中
        private void fileList_SelectedCellsChanged(object sender, SelectedCellsChangedEventArgs e)
        {
            //初始化位置
            Canvas.SetTop(this.step_test_tag, 134);
            string rootPath = ProjectConfig.CommonfileSavePath;
            this.codeText.Text = "";
            //选中一个文件
            DataGrid dataGrid = sender as DataGrid;
            DataFileViewModel curData = (DataFileViewModel)dataGrid.SelectedItem;
            if (curData != null)
            {
                string fileName = FileUtils.getName(curData.fileName);
                //打开文件
                Nex.job_open(fileName, MainWindow.roboteName);

                //加载数据到单步调试
                string jsonFileName = FileUtils.parseFileJsonName(fileName);
                //根据文件名称 加载json文件内容
                RoboteExcuteFile resultDataBody = FileUtils.readUploadFile(rootPath, jsonFileName);
                if (resultDataBody != null)
                {
                    Dictionary<int, string> fileData = resultDataBody.fileContent;
                    //单步调试面包内容加载
                    foreach (var item in fileData)
                    {
                        this.codeText.Text += item.Value + "\n";
                    }

                    int positionLine = resultDataBody.cur_step_line;
                    //计算单步调试动画距离
                    Canvas.SetTop(this.step_test_tag, Canvas.GetTop(this.step_test_tag) + 15 * (positionLine));

                }

            }

        }



        private void runClick(object sender, RoutedEventArgs e)
        {

            DataGrid dataGrid = this.fileList;
            DataFileViewModel c = (DataFileViewModel)dataGrid.SelectedItem;
            string fileName = c.fileName.Substring(0, c.fileName.LastIndexOf("."));
            Nex.job_run(fileName, MainWindow.roboteName);
        }

        private void continuteClick(object sender, RoutedEventArgs e)
        {
            Nex.job_continue(MainWindow.roboteName);
        }


        private void pauseClick(object sender, RoutedEventArgs e)
        {
            Nex.job_pause(MainWindow.roboteName);

        }
        private void stopClick(object sender, RoutedEventArgs e)
        {

            Nex.job_stop(MainWindow.roboteName);

        }


        private void delClick(object sender, RoutedEventArgs e)
        {


            DataGrid dataGrid = this.fileList;
            int curindex = dataGrid.SelectedIndex;
            if (this.fileLists != null)
            {
                this.fileLists.RemoveAt(curindex);
                this.fileList.Items.Refresh();
                this.fileList.ItemsSource = fileLists;
            }


            this.codeText.Text = "";



        }


        public void fileUpload(object sender, RoutedEventArgs e)
        {
            //上传文件总行数
            int lineNumber = 0;
            Dictionary<int, string> fileCode = new Dictionary<int, string>();
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.Filter = "All files (*.*)|*.*";

            if (openFileDialog.ShowDialog() == true)
            {
                string filePath = openFileDialog.FileName;
                string fileName = Path.GetFileName(filePath);

                //上传到上位机
                int result = Nex.job_upload_by_file(filePath, MainWindow.roboteName);

                if (result == 0)
                {
                    MessageBox.Show("上传成功");
                    DataFileViewModel curFile = new DataFileViewModel(fileName, this.fileLists.Count > 0 ? this.fileLists.Count + "" : 0 + "");
                    this.fileLists.Add(curFile);
                }
                //读取文件
                StreamReader file = new StreamReader(filePath);
                string line;
                // 从文件中读取内容
                while ((line = file.ReadLine()) != null)
                {
                    if (line.Contains("//") || line.Contains("///"))
                    {
                        continue;
                    }

                    ++lineNumber;

                    fileCode.Add(lineNumber, line);
                    if (line.Contains("NOP"))
                    {
                        Canvas.SetTop(this.step_test_tag, Canvas.GetTop(this.step_test_tag) + 15 * (lineNumber - 1));
                    }
                }
                this.codeText.Text = "";
                foreach (var item in fileCode)
                {
                    this.codeText.Text += item.Value + "\n";
                }

                //初始化绿点位置
                Canvas.SetLeft(this.step_test_tag, 897);
                Canvas.SetTop(this.step_test_tag, 134);


                string rootPath = ProjectConfig.CommonfileSavePath;

                string saveFilePath = FileUtils.getName(fileName) + ".json";
                //生成以文件名.json 的文件



                RoboteExcuteFile excuteFile = new RoboteExcuteFile();
                excuteFile.cur_step_line = 0;
                excuteFile.parentPath = rootPath;
                excuteFile.curFilePath = saveFilePath;
                excuteFile.fileContent = fileCode;

                string json = JsonConvert.SerializeObject(excuteFile);


                bool writeTag = FileUtils.writeFileByByte(rootPath, saveFilePath, Encoding.Default.GetBytes(json));
                if (writeTag)
                {

                    this.fileList.Items.Refresh();
                    ItemCollection collection = this.fileList.Items;
                     this.fileList.SelectedIndex = 1;
                                    }
                else
                {
                    MessageBox.Show("文件上传失败");
                }





            }
        }

        private void step_run_click(object sender, RoutedEventArgs e)
        {
            string rootPath = ProjectConfig.CommonfileSavePath;
            //Canvas 效果
            Canvas.SetTop(this.step_test_tag, Canvas.GetTop(this.step_test_tag) + 15);

            DataGrid dataGrid = this.fileList;
            DataFileViewModel curSelectData = (DataFileViewModel)dataGrid.SelectedItem;
            //根据总行书  读取所对应行数 机器人指令语句
            if (curSelectData != null)
            {
                string jsonFileName = FileUtils.parseFileJsonName(curSelectData.fileName);
                //根据文件名称 加载json文件内容
                RoboteExcuteFile resultDataBody = FileUtils.readUploadFile(rootPath, jsonFileName);
                Nex.job_step(FileUtils.getName(curSelectData.fileName), resultDataBody.cur_step_line, MainWindow.roboteName);
                resultDataBody.cur_step_line += 1;
                string json = JsonConvert.SerializeObject(resultDataBody);

                bool writeStatus = FileUtils.overWriteJsonContent(rootPath, jsonFileName, json);
                if (writeStatus)
                {
                    //更新

                }


            }
            else
            {
                MessageBox.Show("请选中需要单步调试的文件");
            }





        }
    }
}









